<template>
  <div id="app">
    <!-- 查询 -->
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="queryInfo.name" placeholder="请输入搜索姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryInfo.status" placeholder="全部" clearable>
          <el-option label="启用" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadUsers">查询</el-button>
        <el-button type="success" @click="showAddDialog">添加</el-button>
        <el-button type="danger" @click="removeBatch">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="users" style="width: 100%" border stripe  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="phone" label="电话"> </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
            @change="updateUserStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
          <el-button type="primary" size="small" @click="showEditDialog(scope.row.id)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>


    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="addDialogVisible" :close-on-click-modal="false" @close="handleDialogClose">
      <el-form :model="user" :rules="rules" ref="userFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="user.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="user.address" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {
    HelloWorld
  },
  data() {
    return {
      // 用户列表
      users: [],
      // 表单用户信息
      user: {
        name: '',
        phone: '',
        address: ''
      },
      // 查询条件
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        name: '',
        phone: '',
        status: ''
      },
      // 总条数
      total: 0,
      // 添加对话框是否显示
      addDialogVisible: false,
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ]
      },
      // 对话框的标题
      title: '',
      // 复选框选中的值
      multipleSelection: []
    }
  },
  methods: {
    // 加载用户列表
    async loadUsers() {
      const { data: res } = await this.$http.get('/users/queryByPage', {
        params: this.queryInfo
      })
      this.users = res.data.records
      this.total = res.data.total
    },
    // 添加/编辑用户
    addOrUpdate() {
      // 判断表单校验是否通过
      this.$refs.userFormRef.validate(async valid => {
        // 表单校验未通过，则停止执行
        if (!valid) {
          return
        }

        /**
         * 判断是添加用户还是编辑用户
         */
        if (this.title == '添加用户') {
          const { data: res } = await this.$http.post('/users/add', this.user)
          if (res.status != 200) {
            return this.$message.error('添加失败')
          }
          this.$message.success('添加成功')
        } else {
          const { data: res } = await this.$http.put('/users/modify', this.user)
          if (res.status != 200) {
            return this.$message.error('修改失败')
          }
          this.$message.success('修改成功')
        }

        // 重新加载数据
        this.loadUsers()
        // 关闭对话框
        this.addDialogVisible = false
      })
    },
    // 修改用户状态
    async updateUserStatus(user) {
      console.log(user)
      // 向后端发送请求
      const { data: res } = await this.$http.put(`/users/modifyStatus/${user.id}/${user.status}`)
      if (res.status != 200) {
        return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
    },
    // 根据id删除用户
    deleteUser(id) {
      // 弹出提示框
      this.$confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 向后端发送请求
        const { data: res } = await this.$http.delete(`/users/remove/${id}`)
        if (res.status != 200) {
          return this.$message.error('删除失败')
        }
        // 显示删除成功的提示
        this.$message.success('删除成功')
        // 重新加载数据
        this.loadUsers()
      }).catch(() => {
        this.$message.info('已取消删除')
      });

    },
    // 监听页大小的改变
    handleSizeChange(val) {
      this.queryInfo.pageSize = val
      this.loadUsers()
    },
    // 监听页码的改变
    handleCurrentChange(val) {
      this.queryInfo.pageNum = val // 修改当前页码
      this.loadUsers() // 重新加载数据
    },
    // 监听对话框的关闭
    handleDialogClose() {
      // 重置表单
      this.$refs.userFormRef.resetFields()
    },
    // 显示添加对话框
    showAddDialog() {
      this.title = '添加用户'
      this.addDialogVisible = true
    },
    // 显示编辑对话框
    async showEditDialog(id) {
      // 根据id获取用户信息
      const { data: res } = await this.$http.get('/users/findById?id=' + id)
      this.user = res.data

      this.title = '编辑用户'
      this.addDialogVisible = true
    },
    // 批量删除
    removeBatch(){
      // 弹出提示框
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 获取要删除的用户的id
        var ids = []
        this.multipleSelection.forEach(item => {
          ids.push(item.id)
        })
        // 向后端发送请求
        const { data: res } = await this.$http.delete(`/users/removeBatch`, {
          data: ids
        })
        if (res.status != 200) {
          return this.$message.error('删除失败')
        }
        // 显示删除成功的提示
        this.$message.success('删除成功')
        // 重新加载数据
        this.loadUsers()
      }).catch(() => {
        this.$message.info('已取消删除')
      });
    },
    // 监听复选框的变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  },
  created() {
    this.loadUsers()
  }
}
</script>

<style>
.el-pagination {
  text-align: center;
}
</style>
